package com.adinnet.common.utils;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.util.*;

@Slf4j
public class MD5Util {

    /**
     * IC卡加密结果
     * @param key
     * @param map
     * @return
     */
    public static String icSign(String key,Map<String,Object> map){
        return MD5(getOrderByLexicographic(key,map),"UTF-8");
    }


    /**
     * MD5加密
     * @param str 内容
     * @param charset 编码方式
     * @throws Exception
     */
    @SuppressWarnings("unused")
    public static String MD5(String str, String charset) {
        StringBuffer sb = new StringBuffer(32);
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes(charset));
            byte[] result = md.digest();
            for (int i = 0; i < result.length; i++) {
                int val = result[i] & 0xff;
                if (val <= 0xf) {
                    sb.append("0");
                }
                sb.append(Integer.toHexString(val));
            }
        }catch (Exception e){
            log.error("MD5加密异常：{}",e);
            throw new RuntimeException("MD5加密异常");
        }
        return sb.toString().toLowerCase();
    }

    /**
     * 获取参数的字典排序
     * @param maps 参数key-value map集合
     * @return String 排序后的字符串
     */
    private static String getOrderByLexicographic(String key, Map<String,Object> maps){
        return splitParams(lexicographicOrder(getParamsName(maps)),maps,key);
    }
    /**
     * 获取参数名称 key
     * @param maps 参数key-value map集合
     * @return
     */
    private static List<String> getParamsName(Map<String,Object> maps){
        List<String> paramNames = new ArrayList<String>();
        for(Map.Entry<String,Object> entry : maps.entrySet()){
            String key=entry.getKey().toString();
            if(ObjectUtils.isNotEmpty(maps.get(key))){
                paramNames.add(key);
            }
        }
        return paramNames;
    }

    /**
     * 参数名称按字典排序
     * @param paramNames 参数名称List集合
     * @return 排序后的参数名称List集合
     */
    private static List<String> lexicographicOrder(List<String> paramNames){
        Collections.sort(paramNames);
        return paramNames;
    }


    /**
     * 拼接排序好的参数名称和参数值
     * @param paramNames 排序后的参数名称集合
     * @param maps 参数key-value map集合
     * @return String 拼接后的字符串
     */
    private static String splitParams(List<String> paramNames,Map<String,Object> maps,String key){
        StringBuilder paramStr = new StringBuilder(key);
        for(String paramName : paramNames){
            paramStr.append(paramName).append(maps.get(paramName));
        }
        log.info("所要拼密钥的字符串："+paramStr);
        return paramStr.toString();
    }

    public static void main(String[] args) {
        String appSecret="1234567890";//秘钥

        Map<String, Object> map=new HashMap<String,Object>();
        map.put("appId","diezhi");
        map.put("timestamp","20200716172020");
        map.put("sign","asdasffwvrfewfcwe");

        map.put("type","1");//所要加密的字符串
        map.put("icNo","123123123");
        map.put("posNo","123343243");
        map.put("authoritiesPoint","234234");
        map.put("scene","2342343");
        map.put("test","");
        map.put("test123",null);

        StringBuffer keyStr=new StringBuffer("appId").append(map.get("appId"))
                .append("appSecret").append(appSecret).append("timestamp").append(map.get("timestamp"));

        map.remove("appId");
        map.remove("timestamp");
        map.remove("sign");
        //1，固定排序 + 首字母顺序排序
        //2，key 对应的 value 为空的不参与排序
//        System.out.println("签名结果："+icSign(keyStr.toString(),map));

        //排序结果：appId123123appSecret1234567890timestamp20200716172020authoritiesPoint234234icNo123123123posNo123343243scene2342343type1
        //加密结果：c1fb0e0ac0eae850a64a0f446de192bb

        String str="appIddiezhi{\"version\":\"123\",\"time\":\"20200721121212\",\"nenue_id\":\"xxx\",\"device\":{\"type\":\"008\",\"position\":\"A_1\"},\"data\":{\"value\":\"123456789ABCDEF\",\"power\":\"ON\",\"relay1\":\"ON\",\"relay2\":\"OFF\"}}appSecretABC123";
        System.out.println(MD5(str,"UTF-8"));
    }

}
